/**
 * 日期计算工具函数
 */

import { format, differenceInDays, addDays, isSameDay } from 'date-fns';
import { zhCN } from 'date-fns/locale';

/**
 * 根据开学日期计算当前是第几周
 * @param startDate 开学日期
 * @param currentDate 当前日期
 * @returns 当前周次
 */
export const getCurrentWeek = (startDate: Date, currentDate: Date = new Date()): number => {
  const diffDays = differenceInDays(currentDate, startDate);
  return Math.floor(diffDays / 7) + 1;
};

/**
 * 获取指定周的日期范围
 * @param startDate 开学日期
 * @param weekNumber 周次
 * @returns 该周的开始和结束日期
 */
export const getWeekDates = (startDate: Date, weekNumber: number) => {
  const weekStartDate = addDays(startDate, (weekNumber - 1) * 7);
  const weekEndDate = addDays(weekStartDate, 6);
  return { weekStartDate, weekEndDate };
};

/**
 * 判断指定日期是否是今天
 * @param date 要检查的日期
 * @returns 是否是今天
 */
export const isToday = (date: Date): boolean => {
  return isSameDay(date, new Date());
};

/**
 * 格式化日期为 MM-DD 格式
 * @param date 日期
 * @returns 格式化后的日期字符串
 */
export const formatDate = (date: Date): string => {
  return format(date, 'MM-dd');
};

/**
 * 获取月份名称
 * @param date 日期
 * @returns 月份名称（如"9月"）
 */
export const getMonthName = (date: Date): string => {
  return format(date, 'M月', { locale: zhCN });
};

/**
 * 获取星期名称
 * @param dayOfWeek 星期几 (1-7)
 * @returns 星期名称
 */
export const getDayName = (dayOfWeek: number): string => {
  const dayNames = ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日'];
  return dayNames[dayOfWeek] || '';
};

/**
 * 获取指定周的每天日期信息
 * @param startDate 开学日期
 * @param weekNumber 周次
 * @returns 每天的日期信息数组
 */
export const getWeekDayHeaders = (startDate: Date, weekNumber: number) => {
  const { weekStartDate } = getWeekDates(startDate, weekNumber);
  
  return Array.from({ length: 7 }, (_, index) => {
    const date = addDays(weekStartDate, index);
    const dayOfWeek = index + 1; // 1-7 对应周一到周日
    
    return {
      day: dayOfWeek,
      dayName: getDayName(dayOfWeek),
      date: formatDate(date),
      isToday: isToday(date),
      fullDate: date
    };
  });
};

/**
 * 计算距离学期结束还有多少天
 * @param startDate 开学日期
 * @param totalWeeks 总周数
 * @returns 剩余天数
 */
export const getDaysUntilSemesterEnd = (startDate: Date, totalWeeks: number): number => {
  const semesterEndDate = addDays(startDate, totalWeeks * 7 - 1);
  const today = new Date();
  const remainingDays = differenceInDays(semesterEndDate, today);
  return Math.max(0, remainingDays);
};
